package com.hyt.it.ogt.ks.service.impl;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.feign.KwClient;
import com.hyt.it.ogt.ks.feign.model.EndExamCandidaeDTO;
import com.hyt.it.ogt.ks.mapper.mongodb.CandidateAnswerBackupRepository;
import com.hyt.it.ogt.ks.mapper.mongodb.CandidateAnswerLogRepository;
import com.hyt.it.ogt.ks.model.entity.mongodb.CandidateAnswerLog;
import com.hyt.it.ogt.ks.model.entity.mongodb.CandidateAnswerLogBackup;
import com.hyt.it.ogt.ks.model.vo.AnswerVO;
import com.hyt.it.ogt.ks.model.vo.CandidateQusAnsVO;
import com.hyt.it.ogt.ks.model.vo.QuestionAnswerVO;
import com.hyt.it.ogt.ks.mq.model.CandidateAnswerLogBackupDTO;
import com.hyt.it.ogt.ks.service.CandidateAnswerLogService;
import com.hyt.it.ogt.ks.util.LocalDateTimeUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wuyingge
 * @ClassName CandidateAnswerLogServiceImpl.java
 * @Description 考生保存答案请求参数日志
 * @createTime 2021年10月16日 14:45:00
 */
@Service
@Slf4j
public class CandidateAnswerLogServiceImpl implements CandidateAnswerLogService {
    @Resource
    private CandidateAnswerBackupRepository candidateAnswerBackupRepository;
    @Resource
    private CandidateAnswerLogRepository candidateAnswerLogRepository;
    @Resource
    private KwClient kwClient;

    @Override
    public Boolean consumerLog(CandidateAnswerLogBackupDTO logBackup){
        try {
            if(Objects.isNull(logBackup)){
                log.error("考生保存答案请求参数日志收到入库请求，内容为空!");
                return Boolean.FALSE;
            }
            List<CandidateAnswerLog> logs = new ArrayList<>();
            List<CandidateAnswerLogBackup> backups = new ArrayList<>();
            for(CandidateQusAnsVO answerLog : Optional.ofNullable(logBackup.getAnswerLogs()).orElse(new ArrayList<>())){
                List<QuestionAnswerVO> answers = answerLog.getAnswer();
                if(CollectionUtils.isEmpty(answers)){
                    log.warn("考生保存答案请求参数日志收到入库请求:【{}】，答案内容为空!",answerLog);
                    continue;
                }
                for(QuestionAnswerVO answerVO : answers){
                    List<AnswerVO> userAnswerList = answerVO.getUserAnswerList();
                    if(CollectionUtils.isEmpty(userAnswerList)){
                        CandidateAnswerLog log = CandidateAnswerLog.builder().candidateId(answerLog.getCandidateId()).examId(answerLog.getExamId())
                                .paperSort(answerLog.getPaperSort()).viewAnswerDescription(answerLog.getViewAnswerDescription())
                                .answerTime(answerVO.getAnswerTime()).itemSort(answerVO.getItemSort()).
                                itemId(answerVO.getItemId()).itemType(answerVO.getItemType()).createDate(LocalDateTime.now()).build();
                        logs.add(log);
                        continue;
                    }
                    for(AnswerVO vo : userAnswerList){
                        CandidateAnswerLog log = CandidateAnswerLog.builder().candidateId(answerLog.getCandidateId()).examId(answerLog.getExamId())
                                .paperSort(answerLog.getPaperSort()).viewAnswerDescription(answerLog.getViewAnswerDescription())
                                .answerTime(answerVO.getAnswerTime()).itemSort(answerVO.getItemSort()).
                                itemId(answerVO.getItemId()).itemType(answerVO.getItemType()).createDate(LocalDateTime.now())
                                .optionId(vo.getOptionId()).userAnswer(vo.getUserAnswer()).build();
                        logs.add(log);
                    }
                }
            }
            for(CandidateAnswerLogBackup backup : Optional.ofNullable(logBackup.getAnswerBackups()).orElse(new ArrayList<>())){
                backups.add(backup);
            }
            Boolean success = Boolean.FALSE;
            if(!CollectionUtils.isEmpty(logs)){
                success = candidateAnswerLogRepository.insert(logs).size() > 0;
            }
            if(!CollectionUtils.isEmpty(backups)){
                success = candidateAnswerBackupRepository.insert(backups).size() > 0;
            }
            log.info("------保存考生答案请求日志备份，log条数为{},back条数为:{}",logs.size(),backups.size());
            return success;
        } catch (Exception e){
            log.error("-----保存考生答案请求日志备份,入库过程异常-----，",e);
            return Boolean.FALSE;
        }
    }

    //@Transactional(rollbackFor = Exception.class)
    public Boolean deleteByDate(){
        LocalDateTime endTime = LocalDateTimeUtils.plus(LocalDateTime.now(), 90, ChronoUnit.DAYS);
        String endTimeStr = LocalDateTimeUtils.formatTime(endTime,LocalDateTimeUtils.YYYYMMDDHHMMSS);
        try {
            //1:先查询截至时间之前已结束的考试 todo 暂时没有完成定时删除的功能
            String endEcRsp = kwClient.getEndExamCandidateCount(EndExamCandidaeDTO.builder().build());
            log.info("定期清理考生轨迹及备份表调用教务查询到期考生数量返回信息为：{}",endEcRsp);
            if(StringUtils.isBlank(endEcRsp)){
                log.info("定期清理考生轨迹及备份表调用教务查询到期考生数量返回信息为：空");
                return Boolean.FALSE;
            }
            ApiResponse<Integer> endEcCountResponse = ApiResponse.ConvertRet(endEcRsp,Integer.class);
            if(!Objects.equals(BizStatusCode.KW_SUCCESS_OK,endEcCountResponse.getCode()) || Objects.isNull(endEcCountResponse.getData())){
                log.info("定期清理考生轨迹及备份表调用教务查询到期考生数量失败，返回信息为：【{}】",endEcCountResponse);
                return Boolean.FALSE;
            }
            Integer endEcCount = endEcCountResponse.getData();
            if(endEcCount < 1){
                log.info("定期清理考生轨迹及备份表调用教务查询到期考生数量返回信息显示暂无需要处理数据");
                return Boolean.TRUE;
            }

        } catch (Exception e){
            log.error("定期清理考生轨迹及备份表发生异常,运行时间为:{},异常为:",endTimeStr,e);
        }

        return null;
    }

    /**
     * 通过考生id查询mongodb里的数据
     * @param candidateId
     * @return
     */
    @Override
    public List<CandidateAnswerLog> getCandidateLogsByCandidateId(String candidateId){
        return candidateAnswerLogRepository.findCandidateAnswerLogsByCandidateId(candidateId);
    }
}
